

<template>
  <el-card shadow="hover">
    <!--条件查询-->
    <el-form :inline="true"  :model="studentSearch" class="demo-form-inline" align="left">
      <el-form-item >
        <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
      </el-form-item>
      <el-form-item >
        <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
      </el-form-item>
      <el-form-item >
        <el-select v-model="studentSearch.cid" placeholder="所在班级" style="width: 200px">
          <el-option label="所有班级" value="0"></el-option>
          <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" icon="search" plain>查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="addStudent" icon="plus" plain>添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="studentList"
        style="width: 100%">
      <el-table-column
          label="学号"
          prop="sid"
          align="center" />
      <el-table-column
          label="学生姓名"
          prop="sname"
          align="center" />
      <el-table-column
          label="学生性别"
          prop="sex"
          align="center" />
      <el-table-column
          label="学生住址"
          prop="addr"
          align="center" />
      <el-table-column
          label="所在班级"
          prop="cname"
          align="center" />

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button-group>
          <el-button size="small" type="success" icon="Edit" @click="handleEdit(scope.$index, scope.row)"></el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)" icon="Delete"></el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!--分页导航-->
    <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!--编辑学生用的对话框：-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500px" :close-on-click-modal="false">
      {{student}}
      <el-form :model="student" :rules="rules" ref="studRef">
        <el-form-item label="学生姓名:" :label-width="formLabelWidth" prop="sname">
          <el-input v-model="student.sname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
          <el-radio label="男"  v-model="student.sex">男</el-radio>
          <el-radio label="女"  v-model="student.sex">女</el-radio>
        </el-form-item>
        <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
          <el-input v-model.number="student.age" autocomplete="off" />
        </el-form-item>
        <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
          <el-input v-model="student.addr" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
          <el-select v-model="student.cid" placeholder="请选择班级">
            <el-option label="所有班级" value="0" />
            <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary"  @click="save(studRef)">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
    // 1. 引入访问后台的模块
    import studentApi from '@/api/student'
    import classesApi from '@/api/classes'
    import {ref,onMounted} from 'vue'
    import {ElMessage} from "element-plus";
    const studentList = ref([])       // 学生列表
    const classes = ref({})           // 班级列表
    const studentSearch = ref({})     // 代表要查询的学生对象
    const total = ref(0)              // 总记录数
    const page = ref(1)               // 当前页
    const pageSize = ref(5)           // 每页大小
    const student = ref({})           // 对话框绑定的学生对象
    const dialogFormVisible = ref(false)  // 对话框的可见性，true:可见 false：不可见
    const formLabelWidth = "100px"         // 对话框文本宽度
    const title = ref("添加学生")      // 对话框标题
    const studRef = ref({})           // 定义表单对象

    // 自定义表单验证规则
    const ageValidator = (rule,value,callback) => {
      if (!value){
        return callback(new Error("请输入年龄！"))
      }else  if(!Number.isInteger(value)){
        return callback(new Error("年龄必须是整数！"))
      }else if(value < 1 || value > 150){
        return callback(new Error("年龄必须在1-150之间!"))
      }else{
        return callback()
      }
    }
    // 自定义校验规则
    const rules = ref({
      // 1. 学生姓名的验证
      sname:[
        {required:true,message:'请输入学生姓名!',trigger:'blur'}
      ],
      // 2. 学生性别的验证
      sex:[
        {required:true,message:'请选择学生性别！',trigger:'change'}
      ],
      // 3. 学生年龄的验证（自定义校验器）
      age:[
        // {required:true,message:'请输入学生年龄！',trigger:'blur'}
        {validator:ageValidator,trigger:'blur'}
      ],
      // 4. 学生住址的验证
      addr:[
        {required:true,message:'请输入学生住址！',trigger:'blur'}
      ],
      // 5.学生所有班级的验证
      cid:[
        {required:true,message:'请选择学生所在班级!',trigger:'change'}
      ]
    })

    // 2. 查询所有学生
    const  findStudents = async () => {
      studentList.value = await studentApi.findStudents().data.data
    }
    // 3. 分页查询学生
    const findByPage = async () => {
      const {data} = await studentApi.findByPage(page.value,pageSize.value)
      studentList.value = data.data.rows
      total.value = data.data.total
      console.log(data)
    }
    // 4. 条件查询带分页
    const search = async () => {
      const {data} = await studentApi.search(page.value,pageSize.value,studentSearch.value)
      studentList.value = data.data.rows
      total.value = data.data.total
    }
    // 5. 查询所有班级
    const findClasses = async () => {
        const {data} = await classesApi.findClasses()
        classes.value = data.data
    }
    const handleEdit = (index, row) => {
      console.log(index, row);
      // 1. 修改对话框标题
      title.value = "修改学生"
      // 2. 为student（与表单绑定的）赋值
      student.value = row
      // 3. 打开对话框
      dialogFormVisible.value = true

    }
    const handleDelete = (index, row) => {
      console.log(index, row);
    }
    // 页大小改变时触发
    const handleSizeChange = (val) => {
      pageSize.value = val
      // findByPage()
      search()
      console.log(`每页 ${val} 条`);
    }
    // 当前页发生改变时触发
    const handleCurrentChange = (val) =>  {
      page.value = val
      // findByPage()
      search()
      console.log(`当前页: ${val}`);
    }
    // 添加学生
    const addStudent = () => {
      // 1. 设置对话框标题
      title.value = "添加学生"
      // 2. 将学生对象清空
      student.value = {}
      // 3. 打开对话框
      dialogFormVisible.value = true
    }
    // 提交表单
    const save = async (form1) => {
      console.log(form1)
      await form1.validate( async (valid) => {
        if (valid){       // 如果为true,代表所有的表单控件都验证通过
          // 1. 定义添加或修改的url地址
          let url = '/student/add'
          let method = 'post'
          // 2. 如果sid存在值，证明是修改操作
          if (student.value.sid){
            url = '/student/update'
            method = 'put'
          }
          const {data} = await studentApi.save(url,student.value,method)
          if (data.code === 200){
            ElMessage({
              message: data.msg,
              type: 'success',
              onClose(){
                search()          // 刷新页面
                dialogFormVisible.value = false // 关闭对话框
              }
            })
          }
        }else{            // 如果valid=false,代表至少有一个表单控件验证未通过
          console.log("至少有一个表单控件没通过！")
          return false
        }
      })
    }
    // findByPage()
    search()
    findClasses()
</script>

<style>
.el-pagination{
  margin-top: 20px;
  margin-bottom: 20px;
  text-align: right;
  float:right;
}
</style>
